package com.hc.kotlin_coroutine

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext

//----------runBlocking withContext----------
fun main17() {
    println("Hello")
    var a = runBlocking { //创建一个协程并阻塞当前线程
        delay(1000)
        "World"
    }
    println(a)
    runBlocking (Dispatchers.IO){//指定调度器 模拟网络请求
        request {
            withContext(Dispatchers.Main){//指定调度器 模拟切换至UI线程(需要android、swing、javafx项目)
                println("${Thread.currentThread().name} UI刷新")
            }
        }
    }
}

suspend fun request(finish:suspend ()->Unit){
    delay(1000)
    println("${Thread.currentThread().name} 网络请求成功")
    finish()
}
//----------runBlocking withContext----------
//----------GlobalScope----------
fun main18() {
    var globalScope = GlobalScope
    globalScope.launch { //创建一个协程,生命周期相当于Application
        delay(1000)
        println("Hello")
    }
    GlobalScope.launch {
        delay(1000)
        println("World")
    }
//    globalScope.cancel() //不能手动取消
    Thread.sleep(2000)
}
//----------GlobalScope----------
//----------CoroutineScope----------
fun main19() {
    var coroutineScope = CoroutineScope(Dispatchers.IO)
    CoroutineScope(Dispatchers.Default).launch {//创建一个可控制的协程 指定调度器
        delay(1000)
        println("Hello")
    }
    coroutineScope.launch {
        delay(500)
        println("World")
    }
    coroutineScope.cancel()
    Thread.sleep(3000)
}
//----------CoroutineScope----------
//----------launch----------
fun main20() {
    runBlocking {
        launch(Dispatchers.IO) {//需要一个协程作用域 创建一个协程 指定调度器
            println("Hello ${coroutineContext}")
        }
        val job = launch(start = CoroutineStart.LAZY) {//指定协程启动模式
            println("World ${coroutineContext}")
        }
        job.start()
    }
}
//----------launch----------
//----------async----------
fun main() {
    runBlocking {
        var result = async {//异步带返回值的launch
            delay(1000)
            println("async")
            100
        }
        println("Hello")
        println(result.await())
    }
}
//----------async----------